package com.daisuxia.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.daisuxia.back.utils.ServiceResult;
import com.daisuxia.back.utils.SpringUtils;
import com.daisuxia.back.utils.SysCacheUtils;
import com.daisuxia.constant.Constant;
import com.daisuxia.risk.pojo.RiskCreditUser;
import com.daisuxia.risk.service.IJxlService;
import com.daisuxia.risk.service.IRiskCreditUserService;
import com.daisuxia.web.common.reslult.JsonResult;
import com.daisuxia.web.common.reslult.Status;
import com.daisuxia.web.pojo.BackConfigParams;
import com.daisuxia.web.pojo.MessageTemplate;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.service.IMessageTemplateService;
import com.daisuxia.web.service.IUserService;
import com.daisuxia.web.util.HttpUtil;

import net.sf.json.JSONObject;

/**
 * 用户运营商认证
 * 
 * @author 2016年12月9日 16:51:09
 * @param
 */
@Controller
public class UserJxlApproveController extends BaseController {
	Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private IJxlService jxlService;
	@Autowired
	private IRiskCreditUserService riskCreditUserService;
	@Autowired
	private IUserService userService;
	
	@Autowired
	private IMessageTemplateService messageTemplateService;

	/**
	 * 运营商认证请求
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("/credit-web/verification-jxl")
	public String verificationJxl(HttpServletRequest request, HttpServletResponse response, Model model) {
		long start=System.currentTimeMillis();
		
		String recode = request.getParameter("recode");
		String code = "500";
		String msg = request.getParameter("msg");
		String clientType=request.getParameter("clientType");
		HashMap<String, Object> params = new HashMap<String, Object>();
		String token = null;
		String website = null;
		User user = this.loginFrontUserByDeiceId(request);
		String deviceId = request.getParameter("deviceId");
		String mobilePhone = request.getParameter("mobilePhone");

		if(clientType!=null&&clientType.equals("ios")){
			clientType="ios";

		}else{
			clientType="andriod";
		}
		try {
			if(user==null){
				code = "400";
				msg = "请重新登录";
				model.addAttribute("recode", recode);
				model.addAttribute("code", code);
				model.addAttribute("clientType", clientType);
				return "userinfo/userJxlApproveSucc";
			}

			user = userService.searchByUserid(Integer.valueOf(user.getId()));


			if ("2".equals(user.getJxlStatus())) {
				code = "200";
				msg = "用户已认证";
				model.addAttribute("code", code);
				model.addAttribute("recode", recode);
				model.addAttribute("msg", msg);
				model.addAttribute("clientType", clientType);
				long end=System.currentTimeMillis();
				logger.info("第一步跳转到认证页面耗时："+(end-start)+"  userinfo/userJxlApproveSucc");
				return "userinfo/userJxlApproveSucc";
			}

			String userFcName = user.getFirstContactName();// 第一联系人姓名
			String userFcPhone = user.getFirstContactPhone();// 第一联系人电话
			String userFcRelation = user.getFristContactRelation();// 第一联系人关系
			String userScName = user.getSecondContactName();// 第二联系人关系
			String userScPhone = user.getSecondContactPhone();// 第二联系人关系
			String userScRelation = user.getSecondContactRelation();// 第二联系人关系
			if (userFcRelation != null) {
				if ("1".equals(userFcRelation) || "2".equals(userFcRelation)) {// 父母
					userFcRelation = "1";
				} else if ("3".equals(userFcRelation)
						|| "4".equals(userFcRelation)) {// 子女
					userFcRelation = "3";
				} else if ("5".equals(userFcRelation)) {// 配偶
					userFcRelation = "0";
				}else if ("6".equals(userFcRelation) || "7".equals(userFcRelation)) {
					userFcRelation = "2";
				}
			}
			if (userScRelation != null) {
				if ("1".equals(userScRelation)) {// 同学
					userScRelation = "5";
				} else if ("2".equals(userScRelation)) {// 亲戚
					userScRelation = "2";
				} else if ("3".equals(userScRelation)) {// 同事
					userScRelation = "4";
				} else if ("5".equals(userScRelation)
						|| "4".equals(userScRelation)) {
					userScRelation = "6";
				}
			}
			String contacts = "";
			String contacts2 = "";
			if (userFcName != null && userFcPhone != null
					&& userFcRelation != null) {
				contacts = "{contact_tel:\"" + userFcPhone
						+ "\",contact_name:\"" + userFcName
						+ "\",contact_type:\"" + userFcRelation + "\"}";
			}
			if (userScName != null && userScPhone != null
					&& userScRelation != null) {
				contacts2 = ",{contact_tel:\"" + userScPhone
						+ "\",contact_name:\"" + userScName
						+ "\",contact_type:\"" + userScRelation + "\"}";
			}
			params.put("userName", user.getRealname());
			params.put("cardNum", user.getIdNumber());
			params.put("userPhone", user.getUserPhone());
			params.put("userId", user.getId());
			params.put("contacts", contacts + contacts2);
			ServiceResult serviceResult = jxlService.getToken(params);
			if (serviceResult.isSuccessed()) {
				token = serviceResult.getMsg();
				website = serviceResult.getExt().toString();
				code = "0";
				if (StringUtils.isNotBlank(msg)) {
					msg += "";
				}
			} else {
				msg = serviceResult.getMsg();
			}
			logger.info("jxl getToken success");
		} catch (Exception e) {
			logger.error("jxl getToken error deviceId="+deviceId, e);
			code = "500";
			msg = "系统异常";
		} finally {
			if (recode != null && "300".equals(recode)) {
				msg = "密码错误";
			} else if (recode != null && "400".equals(recode)) {
				msg = "请填写有效数据";
			} else if (recode != null && "500".equals(recode)) {
				msg = "重新发起认证流程";
			}
		}
		model.addAttribute("clientType", clientType);
		model.addAttribute("mobilePhone", mobilePhone);
		model.addAttribute("deviceId", deviceId);
		model.addAttribute("code", code);
		model.addAttribute("msg", msg);
		model.addAttribute("token", token);
		model.addAttribute("website", website);
		model.addAttribute("userPhone", user.getUserPhone());
		
		long end=System.currentTimeMillis();
		logger.info("第一步跳转到认证页面耗时："+(end-start));
		return "userinfo/userJxlApprove";
	}

	/**
	 * 运营商认证获得验证码
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("/credit-web/mobileApproveGetCap")
	public String mobileApproveCap(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		long start=System.currentTimeMillis();
		String code = "500";
		String msg = "查询失败！";
		String token = request.getParameter("token");
		String website = request.getParameter("website");
		String password = request.getParameter("password");
		String queryPwd = request.getParameter("queryPwd");
		String deviceId = request.getParameter("deviceId");
		String mobilePhone = request.getParameter("mobilePhone");
		String clientType=request.getParameter("clientType");
		User user = this.loginFrontUserByDeiceId(request);

		ServiceResult serviceResults = new ServiceResult("500", "未知异常，请稍后重试！");
		HashMap<String, Object> params = new HashMap<String, Object>();
		try {
			if(user==null){
				code = "400";
				msg = "请重新登录";
				
				model.addAttribute("code", code);
				model.addAttribute("clientType", clientType);
				model.addAttribute("deviceId", deviceId);
				return "userinfo/userJxlApproveSucc";
			}

			if (website != null && token != null && password != null) {
				user = userService.searchByUserid(Integer.valueOf(user.getId()));
				params.put("userPhone", user.getUserPhone());
				params.put("userId", user.getId());
				params.put("website", website);
				params.put("password", password);
				params.put("token", token);
				if (queryPwd != null) {
					params.put("queryPwd", queryPwd);
				}
				serviceResults = jxlService.getCaptcha(params);// 获得验证码请求

				logger.info("jxl getCaptcha success");
				model.addAttribute("clientType", clientType);
				if ("100".equals(serviceResults.getCode())) {// code为100时。用户不需要输入密码。直接认证成功。
					code = "200";
					msg = "提交成功！并开始采集数据";
					if (token != null) {
						RiskCreditUser riUser = new RiskCreditUser(
								Integer.valueOf(user.getId()));
						riUser.setJxlToken(token);
						riskCreditUserService.updateJxlToken(riUser);// 认证成功，修改用户状态
					}

					model.addAttribute("code", code);
					model.addAttribute("deviceId", deviceId);
					model.addAttribute("clientType", clientType);
					long end=System.currentTimeMillis();
					logger.info("第二步获取短信验证码耗时："+(end-start)+": "+"userinfo/userJxlApproveSucc");
					return "userinfo/userJxlApproveSucc";
				} else if ("200".equals(serviceResults.getCode())) {// 发送验证码
					code = "200";
					msg = "验证码发送成功！";
				} else if ("400".equals(serviceResults.getCode())) {
					code = "400";
					msg = "重新发起流程，请输入有效数据！";
					model.addAttribute("recode", code);
					model.addAttribute("deviceId", deviceId);
					long end=System.currentTimeMillis();
					logger.info("第二步获取短信验证码耗时："+(end-start)+": "+"redirect:/credit-web/verification-jxl");
					return "redirect:/credit-web/verification-jxl";
				} else if ("500".equals(serviceResults.getCode())) {
					code = "500";
					msg = "请求失败，请重新发起流程！";
					model.addAttribute("recode", code);

					model.addAttribute("deviceId", deviceId);
					long end=System.currentTimeMillis();
					logger.info("第二步获取短信验证码耗时："+(end-start)+": "+"redirect:/credit-web/verification-jxl");
					return "redirect:/credit-web/verification-jxl";
				} else {// 请求成功，返回失败信息
					msg = serviceResults.getMsg();
					model.addAttribute("msg", msg);

					model.addAttribute("deviceId", deviceId);
					model.addAttribute("mobilePhone", mobilePhone);
					long end=System.currentTimeMillis();
					logger.info("第二步获取短信验证码耗时："+(end-start)+": "+"redirect:/credit-web/verification-jxl");
					return "redirect:/credit-web/verification-jxl";
				}

				logger.info("jxl getcap success");
			} else {
				code = "500";
				msg = "请输入有效数据！";
				model.addAttribute("deviceId", deviceId);
				return "redirect:/credit-web/verification-jxl";
			}
		} catch (Exception e) {
			code = "500";
			msg = "系统异常！";
			logger.error("mobileApprove error ", e);
		}
		model.addAttribute("deviceId", deviceId);
		model.addAttribute("queryPwd", queryPwd);
		model.addAttribute("token", token);
		model.addAttribute("website", website);
		model.addAttribute("password", password);
		model.addAttribute("code", code);
		model.addAttribute("msg", msg);
		model.addAttribute("mobilePhone", mobilePhone);
		model.addAttribute("userPhone", user.getUserPhone());
		long end=System.currentTimeMillis();
		logger.info("第二步获取短信验证码耗时："+(end-start));
		return "userinfo/userJxlApproveCap";

	}

	/**
	 * 运营商认证提交验证码
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("/credit-web/mobileApproveSub")
	public String mobileApprove(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		long start=System.currentTimeMillis();
		String code = "500";
		String msg = "查询失败！";
		String token = request.getParameter("token");
		String website = request.getParameter("website");
		String password = request.getParameter("password");
		String queryPwd = request.getParameter("queryPwd");
		String needQueryPwd = request.getParameter("needQueryPwd");
		String captcha = request.getParameter("SUBMIT_CAPTCHA");
		String deviceId = request.getParameter("deviceId");
		String mobilePhone = request.getParameter("mobilePhone");
		String clientType=request.getParameter("clientType");
		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");

		HashMap<String, Object> params = new HashMap<String, Object>();
		User user = this.loginFrontUserByDeiceId(request);
		model.addAttribute("deviceId", deviceId);
		model.addAttribute("mobilePhone", mobilePhone);
		try {
			if(user==null){
				code = "400";
				msg = "请重新登录";
				model.addAttribute("code", code);
				model.addAttribute("clientType", clientType);
				long end=System.currentTimeMillis();
				logger.info("第3步获取短信验证码耗时："+(end-start)+" userinfo/userJxlApproveSucc");
				return "userinfo/userJxlApproveSucc";
			}
			if (captcha != null && token != null) {
				model.addAttribute("clientType", clientType);
				user = userService.searchByUserid(Integer.valueOf(user.getId()));
				params.put("CAPTCHA", captcha);
				params.put("userPhone", user.getUserPhone());
				params.put("userId", user.getId());
				params.put("password", password);
				params.put("token", token);
				params.put("website", website);
				if (needQueryPwd != null && needQueryPwd.equals("need")) {
					params.put("queryPwd", queryPwd);
				}
				ServiceResult serviceResults = new ServiceResult("500", "未知异常，请稍后重试！");
				serviceResults = jxlService.applyCollect(params);//提交验证码请求
				if ("100".equals(serviceResults.getCode())//code为100时，需要重新输入验证码
						|| "102".equals(serviceResults.getCode())) {
					code = "100";
					msg = "请输入有效验证码";
					model.addAttribute("token", token);
					model.addAttribute("website", website);
					if ("100".equals(serviceResults.getCode())) {
						model.addAttribute("needQueryPwd", "need");
					}
					model.addAttribute("code", code);
					model.addAttribute("msg", msg);
					model.addAttribute("queryPwd", queryPwd);
					model.addAttribute("userId", user.getId());
					model.addAttribute("userPhone", user.getUserPhone());
					model.addAttribute("CAPTCHA", "");
					long end=System.currentTimeMillis();
					logger.info("第3步获取短信验证码耗时："+(end-start)+" userinfo/userJxlApproveCap");
					return "userinfo/userJxlApproveCap";
				} else if ("200".equals(serviceResults.getCode())) {//code为200时，提交认证请求，开始数据采集
					code = "200";
					msg = "提交验证码成功！并开始采集数据";
					if (token != null) {
						if (user.getId() != null) {
							RiskCreditUser riUser = new RiskCreditUser(
									Integer.valueOf(user.getId()));
							riUser.setJxlToken(token);
							riskCreditUserService.updateJxlToken(riUser);//认证成功修改用户状态
						}
					}
					model.addAttribute("code", code);
					model.addAttribute("msg", msg);
					long end=System.currentTimeMillis();
					logger.info("第3步获取短信验证码耗时："+(end-start)+" userinfo/userJxlApproveSucc");
					return "userinfo/userJxlApproveSucc";
				} else {
					code = "400";
					model.addAttribute("recode", code);
					long end=System.currentTimeMillis();
					logger.info("第3步获取短信验证码耗时："+(end-start)+" redirect:/credit-web/verification-jxl");
					return "redirect:/credit-web/verification-jxl";
				}
			}
		} catch (Exception e) {
			code = "500";
			msg = "系统异常！";
			logger.error("jxl mobileApprove error ", e);
		}
		model.addAttribute("token", token);
		model.addAttribute("code", code);
		model.addAttribute("msg", msg);
		model.addAttribute("deviceId", deviceId);
		model.addAttribute("mobilePhone", mobilePhone);
		long end=System.currentTimeMillis();
		logger.info("第3步获取短信验证码耗时："+(end-start));
		return "userinfo/userJxlApproveSucc";
	}
	/**
	 * 运营商认证找回密码
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("/credit-web/jxlfindPwd")
	public String jxlfindPwd(HttpServletRequest request,HttpServletResponse response, Model model) {
		//ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
		return "userinfo/findJxlPwd";
	}
	
	@RequestMapping("/credit-web/findJxlPwdMore")
	public String findJxlPwdMore(HttpServletRequest request,HttpServletResponse response, Model model) {
		//ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
        String type= request.getParameter("type");
        if(StringUtils.isBlank(type)){
        	type = "1";
        }
        model.addAttribute("type", type);
		return "userinfo/findJxlPwdMore";
	}
	@RequestMapping("/zhima/jxlA")
	public String jxlA(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("userId", "909");
		params.put("token", "6cf543b218d344ff930e8841e9de8824");
		//serviceResult = jxlService.findUserReport(params);
//		System.out.println(serviceResult.getMsg());
		return "userinfo/aaa";
	}

	/**
	 * 查询手机号码归属地
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("/credit-web/findMobileBelong")
	public void findMobileBelong(HttpServletRequest request,HttpServletResponse response, Model model) {
		JsonResult rest = new JsonResult(Status.ERROR.getName(),Status.ERROR.getValue());
		try {
			User user = this.loginFrontUserByDeiceId(request);

			user = userService.searchByUserid(Integer.valueOf(user.getId()));
			String phone = request.getParameter("phone");
			if(!StringUtils.isNotBlank(phone)){
				phone = user.getUserPhone();
			}
			Map<String, String> keys = SysCacheUtils.getConfigParams(BackConfigParams.JXL);
			String sendPhone = "";
			String jxlName="";
			String jxlType="";
			//系统原本查询手机归属地api,新号码可能查询有问题 返回格式如下
			//{"msg":"success","result":{"city":"长沙市","cityCode":"0731","mobileNumber":"1536413","operator":"电信CDMA卡","province":"湖南","zipCode":"410000"},"retCode":"200"}
			String url =keys.get("JXL_MOBILE_BELONG")+"?key="+Constant.JXL_FIND_MOBILE_BELONG_KEY+"&phone="+phone;
			String result =HttpUtil.getInstance().doGet(url);
			JSONObject json = null;
			json = JSONObject.fromObject(result);
			JSONObject  obj = null;
			if("200".equals(json.getString("retCode"))){
				obj = json.getJSONObject("result");
                if(obj.getString("operator").contains("联通")){
                	jxlName = "联通";
                	sendPhone = Constant.JXL_PHONE_LT;
                	jxlType = "2";
                }else if(obj.getString("operator").contains("移动")){
                	jxlName = "移动";
                	sendPhone = Constant.JXL_PHONE_YD;
                	jxlType = "1";
                }else{
                	jxlName = "电信";
                	sendPhone = Constant.JXL_PHONE_DX;
                	jxlType = "3";
                }
			}else{
				//如果原系统查询手机归属地API有问题调用淘宝的api返回的json格式如下
			/*			__GetZoneResult_ = {
					    mts:'1731793',
					    province:'上海',
					    catName:'中国电信',
					    telString:'17317937114',
						areaVid:'29423',
						ispVid:'138238560',
						carrier:'上海电信'
					}*/
				String tobaoUrl ="https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel="+phone;
				String tobaoResult =HttpUtil.getInstance().doGet(tobaoUrl);
				String baoResult = tobaoResult.substring(tobaoResult.indexOf("{"));
				obj = JSONObject.fromObject(baoResult);
				if(obj.containsKey("mts")){
	                if(obj.getString("catName").contains("联通")){
	                	jxlName = "联通";
	                	sendPhone = Constant.JXL_PHONE_LT;
	                	jxlType = "2";
	                }else if(obj.getString("catName").contains("移动")){
	                	jxlName = "移动";
	                	sendPhone = Constant.JXL_PHONE_YD;
	                	jxlType = "1";
	                }else{
	                	jxlName = "电信";
	                	sendPhone = Constant.JXL_PHONE_DX;
	                	jxlType = "3";
	                }
	                json.put("retCode", "200");
	                json.put("msg", "success"); 
				}else{
					logger.info("淘宝查询手机归属地API可能已经更新,请尽快更新API");
					json.put("retCode", "20101");
					json.put("msg", "查询不到数据");
				}
			}
	        MessageTemplate mt = new MessageTemplate();
	        MessageTemplate msg = null;
	        if(StringUtils.isNoneBlank(jxlName)){
	        	   mt.setOperatorType(jxlName);
	               mt.setProvince(obj.getString("province"));
	               msg = messageTemplateService.findTemplate(mt);
	        }
            String sendMsg = "";
            if(msg != null && StringUtils.isNotBlank(msg.getTemplate())){
            	sendMsg = msg.getTemplate();
            }
            if(jxlType.equals("2")){
            	String msgs = sendMsg.substring(0, sendMsg.lastIndexOf("#")+1);
            	String idNumber = user.getIdNumber().substring(user.getIdNumber().length()-6);
            	sendMsg = msgs + idNumber;
            }
            //电信的号码发送的短信格式为MMCZ#用户名#身份证号码
			if(jxlType.equals("3")){
				StringBuffer sb = new StringBuffer();
				String a = "#";
				String username = user.getRealname();
				String idNumber = user.getIdNumber();
				sb.append("MMCZ");
				sb.append(a);
				sb.append(username);
				sb.append(a);
				sb.append(idNumber);
				sendMsg = sb.toString();
			}
            JSONObject data = new JSONObject();
            data.put("sendMsg", sendMsg);
            data.put("sendPhone", sendPhone);
            data.put("province", obj.getString("province"));
            data.put("jxlName", jxlName);
            data.put("phone", phone);
            data.put("jxlType", jxlType);
            rest.setData(data);
        	rest.setCode(json.getString("retCode"));
			rest.setMsg(json.getString("msg"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		SpringUtils.renderJson(response, rest);
		
	}
}
